package com.teradata.olingo.listener;

import com.alibaba.fastjson.JSON;
import com.teradata.olingo.entity.CcdcODataServerError;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.AsyncEvent;
import javax.servlet.AsyncListener;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Project: edb-core
 * @Description:
 * @Version 1.0
 * @Throws SystemException:
 * @Author: <li>2018/8/10 lyndon Create 1.0
 * @Copyright (c)2018-2018 中央结算公司，版权所有
 * @Modified By:
 */
@Slf4j
public class ODataAsynListener implements AsyncListener {

    public ODataAsynListener() {
    }

    @Override
    public void onComplete(AsyncEvent event) throws IOException {
        /*try {
            AsyncContext asyncContext = event.getAsyncContext();
            ServletResponse response = asyncContext.getResponse();
            ServletRequest request = asyncContext.getRequest();
            PrintWriter out = response.getWriter();
            if (request.getAttribute("timeout") != null &&
                    StringUtils.equals("true", request.getAttribute("timeout").toString())) {//超时
                out.println("后台线程执行超时---【回调】");
                System.out.println("异步servlet【onComplete超时】");
            } else {//未超时
                out.println("后台线程执行完成---【回调】");
                System.out.println("异步servlet【onComplete完成】");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }*/
        //System.out.println("异步servlet完成");
        log.debug("reqId:接收响应");
    }

    @Override
    public void onTimeout(AsyncEvent event) throws IOException {
        ServletRequest request = event.getAsyncContext().getRequest();
        HttpServletResponse response = (HttpServletResponse) event.getAsyncContext().getResponse();

        log.debug("reqId:请求超时");
        response.setStatus(408);
        response.setContentType("application/json");
        response.setHeader("Retry-After", "120");

        CcdcODataServerError ccdcODataServerError = CcdcODataServerError.builder()
                .code("111")
                .msg("timeout")
                .tip("timeout tip")
                .build();
        response.getWriter().write(JSON.toJSONString(ccdcODataServerError));
        //response.getOutputStream().write(JSON.toJSONString(ccdcODataServerError).getBytes());
        event.getAsyncContext().complete();
    }

    @Override
    public void onError(AsyncEvent event) throws IOException {
        //System.out.println("异步servlet错误");
        log.debug("reqId:请求错误");
    }

    @Override
    public void onStartAsync(AsyncEvent event) throws IOException {
        //System.out.println("开始异步servlet");
        log.debug("reqId:接收请求");
    }
}
